Applications / Shopping Cart / Cart Flow
Cart flow
-
Code
1. Adding button in View
ADD CARDBUY NOW2. Add to cookie in javascript
Please note that why we use cookie here. User will add more than one product to the cart. The user added product should be available when the user navigate to other pages in the website. So we need to save the products which user added to the cart in somewhere (cookie or session or database) 1. when click on the 'add to cart' button, 'add_to_cart' referece of button will be trigger the given funtion
2. in the function we use cookie variable 'cart_item'. It contains json string data (multiple products)
3. the function 'JSON.parse()' is used to convert the json string to array object
4. then function 'findIndex()' is used to check the user selected product exists in the cart or not
5. if exists, increase the quantity of the product
6. if not exists, add new object of the product to the array using 'push()'
7. again convert the array object to json string to save in the cookie using 'JSON.stringify()'
$(document).on('click', '.add_to_cart', function () { var item_id=$(this).attr('data-id'); var data_type=$(this).attr('data-type'); var title=$(this).parent().parent().parent().find('.data-title').text(); var price=$(this).parent().parent().parent().find('.data-price').text(); var cartItem=[]; var cartItemTotal=0; if ($.cookie('cart_item')) { cartItem=JSON.parse($.cookie("cart_item")); } indexOfObject = cartItem.findIndex((obj => obj.item_id == item_id)); if(indexOfObject>=0){ var total= (cartItem[indexOfObject].quantity+1)*cartItem[indexOfObject].price cartItem[indexOfObject].quantity = cartItem[indexOfObject].quantity+1; cartItem[indexOfObject].total = total; } else{ cartItem.push({'item_id':item_id, 'price':price, 'quantity':1, 'title':title}); } cartItemTotal=cartItem.length; $('.cart_item_total').text(cartItemTotal); $.cookie("cart_item",JSON.stringify(cartItem), { path: '/' }); $.toast({ text : "Successfully added to your cart", showHideTransition : 'fade', // It can be plain, fade or slide bgColor : 'green', // Background color for toast textColor : '#eee', // text color allowToastClose : false, // Show the close button or not hideAfter : 5000, // `false` to make it sticky or time in miliseconds to hide after stack : 5, // `fakse` to show one stack at a time count showing the number of toasts that can be shown at once textAlign : 'left', // Alignment of text i.e. left, right, center position : 'top-right' // bottom-left or bottom-right or bottom-center or top-left or top-right or top-center or mid-center or an object representing the left, right, top, bottom values to position the toast on page }); if(data_type=='buynow'){ window.location.href=CART_URL; } }); 3. show all cart items in a page
route
Route::get('/cart', [OrderController::class, 'cart'])->name('cart'); in controller
public function cart(Request $r) { $cartItems=json_decode($_COOKIE['cart_item'],1); $this->data['cartItem']=[]; $cartTotal=0; foreach($cartItems as $row){ $product=Product::join('pages','pages.id','=','products.page_id') ->select('pages.title','pages.slug_url','pages.image','pages.content','products.*') ->where('products.id', $row['item_id'])->first()->toArray(); $price=$this->data['VISITOR_IP_COUNTRY']=='INR' ? $product['price_inr'] : $product['price_usd']; $this->data['cartItem'][]= [ 'item_id'=>$product['id'], 'title'=>$product['title'], 'price'=>$price, 'currency'=>$this->data['VISITOR_IP_COUNTRY']=='INR' ? '₹' :'$', 'image'=>$product['image'], 'delivery_info'=>$product['delivery_info'], 'delivery_days'=>$product['delivery_days'], 'quantity'=>$row['quantity'] ]; $cartTotal=$cartTotal+($price*$row['quantity']); } $this->data['cartTotal']=$cartTotal; if(Session::get('user')){ $this->data['user']=Session::get('user'); } if(Auth::id()){ $this->data['delivery_address']=Address::where('user_id', Auth::id())->where('default_delivery','1')->first(); } return view('fe.cart',$this->data); } View
1. check user is logged in or not
2. if logged in, need 'delivery_id' hidden field
3. if logged in, show current delivery address
4. if not logged in, show sign in button for loggin
?php if(isset($user) && $user->id>0){ ?> {$delivery_address->firstname} {$delivery_address->lastname}, {$delivery_address->address}, {$delivery_address->city}, {$delivery_address->state}, {$delivery_address->country}-{$delivery_address->pin}
Lankmark : {$delivery_address->landmark},
Mobile: {$delivery_address->mobile} ?php } else{ ?> Sign in ?php } ?>5. show cart items
?php if(isset($cartItem)){ foreach($cartItem as $iRow){ ?> {$iRow['title']}{$iRow['currency']}{$iRow['price']}Delivery by {$iRow['delivery_days']} {$iRow['delivery_info']}7. show cart summary
Payment integration when click on 'PLACE ORDER' button
1. need razorpay.com library checkout.js
2. 'place_order' reference call the place_order route using ajax
3. function 'doPyament()' is used for openning the razor payment window. It is called in the success of ajax call (place_order)
4. after the payment, we need to verify the payment using verifyPayment(). inside the verifyPayment(), we use ajax call and pass razorpay_payment_id which we got from razor pay